package com.wisdom.smartbook.permission;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.wisdom.smartbook.utils.KLog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * 6.0动态权限工具类
 */
public class PermissionUtils {

    private static volatile PermissionUtils sInstance;
    private onPermissionsResultListener mOnPermissionsResult;
    /**
     * 权限请求码
     */
    private int mRequestCode = 1000;
    /**
     * 常用权限
     */
    private String[] permissions = {
            //相机
            Manifest.permission.CAMERA,
            //文件
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            //电话状态
            Manifest.permission.READ_PHONE_STATE,

    };


    /**
     * 常用权限
     */
    private String permCamera =
            //相机
            Manifest.permission.CAMERA;

    private PermissionUtils() {

    }

    public static PermissionUtils getInstance() {
        if (sInstance == null) {
            synchronized (PermissionUtils.class) {
                if (sInstance == null) {
                    sInstance = new PermissionUtils();
                }
            }
        }
        return sInstance;
    }

    public void checkPermissionsCamera(Activity activity, @NonNull onPermissionsResultListener onPermissionsResult) {
        mOnPermissionsResult = onPermissionsResult;
        //6.0才用动态权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mOnPermissionsResult.onPermissionGranted();
            return;
        }

        if (ContextCompat.checkSelfPermission(activity, permCamera) != PackageManager.PERMISSION_GRANTED) {
            //申请权限
            ActivityCompat.requestPermissions(activity, new String[]{permCamera}, mRequestCode);
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            mOnPermissionsResult.onPermissionGranted();
        }
    }

    /**
     * 检察权限
     *
     * @param context
     * @param onPermissionsResult 回调接口
     */
    public void checkPermissions(Activity context, @NonNull onPermissionsResultListener onPermissionsResult) {
        mOnPermissionsResult = onPermissionsResult;
        //6.0才用动态权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mOnPermissionsResult.onPermissionGranted();
            return;
        }
        //创建一个mPermissionList，逐个判断哪些权限未授予，未授予的权限存储到mPermissionList中
        List<String> mPermissionList = new ArrayList<>();
        //逐个判断你要的权限是否已经通过
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                //添加还未授予的权限
                mPermissionList.add(permission);
            }
        }
        //申请权限
        if (mPermissionList.size() > 0) {
            //有权限没有通过，需要申请
            ActivityCompat.requestPermissions(context, permissions, mRequestCode);
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            mOnPermissionsResult.onPermissionGranted();
        }

    }

    /**
     * 请求权限后回调的方法
     *
     * @param requestCode  是我们自己定义的权限请求码
     * @param permissions  是我们请求的权限名称数组
     * @param grantResults 是我们在弹出页面后是否允许权限的标识数组，数组的长度对应的是权限名称数组的长度，数组的数据0表示允许权限，-1表示我们点击了禁止权限
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        KLog.d("onRequestPermissionsResult()");
        if (mRequestCode == requestCode) {
            // 点击了禁止权限，未申请通过的权限
            ArrayList<String> permissionList = new ArrayList<>();
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    permissionList.add(permissions[i]);
                }
            }
            if (mOnPermissionsResult != null) {
                if (permissionList.size() > 0) {
                    //如果有权限没有被允许
                    mOnPermissionsResult.onPermissionDenied(permissionList, getPermissionsHint(permissionList));
                } else {
                    //全部权限通过
                    mOnPermissionsResult.onPermissionGranted();
                }
            }
        }
    }

    private String getPermissionsHint(List<String> permissionList) {
        ArrayList<String> list = new ArrayList<>();
        for (String permission : permissionList) {
            switch (permission) {
                case Manifest.permission.CAMERA:
                    list.add("相机");
                    break;
                case Manifest.permission.READ_EXTERNAL_STORAGE:
                case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                    list.add("读写手机存储");
                    break;
                case Manifest.permission.READ_PHONE_STATE:
                    list.add("获取手机信息");
                    break;
                default:
                    break;
            }
        }
        ArrayList<String> strings = new ArrayList<>(new HashSet<>(list));
        StringBuilder hint = new StringBuilder();
        hint.append("使用此功能需要");
        for (int i = 0; i < strings.size(); i++) {
            if (i == strings.size() - 1) {
                hint.append(strings.get(i));
            } else {
                hint.append(strings.get(i));
                hint.append("、");
            }
        }
        hint.append("权限，请点击“设置”-“权限”打开所需要的权限。");
        return hint.toString();
    }

    /**
     * 权限结果返回借口
     */
    public interface onPermissionsResultListener {
        /**
         * 权限申请通过
         */
        void onPermissionGranted();

        /**
         * 权限申请不通过，跳转到系统设置权限页面，或者直接关闭页面，不让他继续访问
         *
         * @param permissionList  申请不通过的权限集合
         * @param permissionsHint 申请不通过的权限，系统设置权限页面提示语
         */
        void onPermissionDenied(List<String> permissionList, String permissionsHint);
    }

    public void onDestroy() {
        sInstance = null;
        mOnPermissionsResult = null;
    }
}